#include "CModule.h"
#include "commlib.h"

static int md_common_entry(void* param) {
	CModule* thes = (CModule*)param;
    char buf[128] = {0};
    unsigned short msg_len = 0;
    CMsg* msg = (CMsg*)&buf[0];
	while (1) {
		while(SEM_WAIT_OK != thes->sem.wait(&thes->sem)) {
            //sleep(1);
        }
		if(POP_OK == thes->q.pop(&thes->q, (char*)msg, &msg_len)) {
            thes->exeMsg(thes, msg);
        }
	}
    return 0;
}

static int md_run(struct _cmodule_* md) {
	md->th.run(&md->th);
	return 0;
}

static int sendMsg(struct _cmodule_* md, CMsg* msg) {
	if(PUSH_OK == md->q.push(&md->q, (char*)msg, sizeof(msg->msg_id) + sizeof(msg->data_len) + msg->data_len)) {
        md->sem.signal(&md->sem);
    }
	return 0;
}

// static int cmodule_exeMsg(CModule* thes, CMsg* msg) {
    // CMap* m = &thes->msgid_func_map;
    // MODULE_EXEMSG_FN fn = (MODULE_EXEMSG_FN)m->find(m, (void*)msg->msg_id);
    // if(fn) {
        // (*fn)(thes, msg);
    // } else {
        //error log output
    // }
    // return 0;
// }

#define TASK_PRIORITY_DEFAULT   100
int construct_module(CModule* thes, const char* module_name, MODULE_EXEMSG_FN onMsg) {
	construct_queue(&thes->q, WRITE_LOCK);
	construct_sem(&thes->sem, 0);
	construct_task(&thes->th, TASK_PRIORITY_DEFAULT, md_common_entry, thes, module_name);

	if (strlen(module_name) > MODULE_NAME_MAX) {
		memcpy(thes->module_name, module_name, MODULE_NAME_MAX);
		thes->module_name[MODULE_NAME_MAX] = '\0';
	} else {
		strcpy(thes->module_name, module_name);
	}

	thes->run = md_run;
	thes->sendMsg = sendMsg;
    thes->exeMsg = onMsg;//cmodule_exeMsg;
	return 0;
}
